<?php
  require_once('../config.inc.php');

   require_once($config['app_dir'] . '/classes/staff.class.php');
   require_once($config['app_dir'] . '/includes/db.class.php');
   require_once($config['app_dir'] . '/includes/mailer.class.php');
   require_once($config['app_dir'] . '/includes/template.class.php');
   require_once($config['app_dir'] . '/classes/calcplot.class.php');
   require_once($config['app_dir'] . '/classes/class.calc2.php');
   require_once($config['app_dir'] . '/classes/log.class.php');
   require_once($config['app_dir'] . '/classes/translation.class.php');
   require_once($config['app_dir'] . '/classes/user.class.php');


   //------------------------------------------------------------------------------------------------
   class objMailshot extends objStaff  {
   		var $logContent = "";
   		public $loging = true;
   		var $emailsArr = Array();
   		var $notificationsArr = Array();
   		var $namesArr = Array();
   		var $langArr = Array();
   		var $activeArr = Array();
   		var $emailsArr3 = Array();
   		var $namesArr3 = Array();
   		var $mailSubject;
   		var $mailTemplate = "";
   		var $subscrLink = "";
   		var $mailFrom = "IntelliForex Support";
   		var $mailMode = "EmailTrial";
   		var $supportAddr = "stats@intelli4x.com";
   		var $supportFromAddr = "support@intelli4x.com";
   		//var $supportAddr = "alexander.ganchuk@gmail.com";
   		var $TrialDays = 14;
   		var $trialDaysLeft;
   		var $subscrDays = 0;
      	var $subscrDaysLeft = 0;
      	var $subscrTimestmp;
      	var $pipsPeriod = 14;
      	var $subscrPipsPeriod = 30;
      	var $refundArr = Array();
      	var $lang = Array();
		var $userList = Array();

		var $gImageName = ' Equity Curve.gif';
      	var $gImagePath = "";
      	public  $TranslationMessage = false;

		function __construct() {
			$db = $this->db = $this->_db = objDataBase::GetInstance();//new objDataBase();
			parent::__construct(false);

            $TranslationMessage = objTranslationMessage::GetInstance();
            //$TranslationMessage->SetLang('ru');
			$this->TranslationMessage= $TranslationMessage;

         	//$this->user_id = $user_id;
      	} //constructor

      	 protected function StartLog() {
            $this->Log  = new objTextLog('mailerBatch');
        } //StartLog

        protected function StartLogSMS() {
            $this->Log  = new objTextLog('mailerSMS');
        } //StartLog



      public function getUserPips() {
         if( !$this->db ) return false;
         $userPips =  array();
         $itemPips;
         $floatPips = 0;
         $finalPrice;
         $pips = $this->pipsPeriod;
         if ($this->subscrPipsPeriod!=0) $pips = $this->subscrPipsPeriod;
         $startTime = 1180800000;
         //echo $startTime;
         $endTime = time();
         //$query = "SELECT f.BeginPrice,f.ClosePrice,t.DefaultSpread FROM fa_forecast f LEFT JOIN fa_trades t ON f.TradeID=t.TradeID WHERE f.BeginTime>='".$startTime."' AND f.CloseTime<'".$endTime." AND f.ClosePrice>0' ORDER BY f.BeginTime";
         $query = " SELECT (f.CloseTime is null) as FlagActive, f.BeginPrice, f.BeginTime,f.EndPrice,f.EndTime,t.TradeID,f.StopPrice, f.Side,".
         		" round((1 - 2 * f.Side) * (COALESCE(f.ClosePrice, lq.LastClosePrice) - f.BeginPrice) / t.PipSize) as Profit,".
                " FROM_UNIXTIME(f.BeginTime,'$this->_db_show_date') as OpenTimeF, " .
                " FROM_UNIXTIME(f.CloseTime,'$this->_db_show_date') as CloseTimeF, " .
                " COALESCE(f.CloseTime,lq.LastCloseTime) as CloseTime,   ".
                " COALESCE(f.ClosePrice,lq.LastClosePrice) as ClosePrice   ".

            " FROM vfa_forecast f ".
                   " LEFT OUTER JOIN fa_trades t ON (f.TradeID = t.TradeID) ".
                   " LEFT OUTER JOIN ".
                     "(  ".
                      " SELECT ".
                           " ttq.TradeID, ".
                           " ttq.C as LastClosePrice, ".
                           " ttq.TimeStart as LastCloseTime ".
                      " FROM fa_quotes ttq ".
                          " RIGHT OUTER JOIN ( ".
                                " SELECT tq.TradeID, max(tq.TimeStart) as max_quote_time ".
                                " FROM fa_quotes tq ".
                                " GROUP BY tq.TradeID) qq ".
                                " ON (qq.max_quote_time=ttq.TimeStart and qq.TradeID=ttq.TradeID) ".
                    " ) lq ".
                    " ON (f.TradeID = lq.TradeID) ".
         " WHERE f.BeginTime>=$startTime AND f.BeginTime<=$endTime ".
         "ORDER BY (f.CloseTime is null) DESC, COALESCE(f.CloseTime, 0) DESC, f.BeginTime DESC";

         try {
           $rs = $this->db->Execute($query);
	           if ($rs){
					while (!$rs->EOF) {
                        //$itemPips = $rs->fields['Profit'];
                        $userPips[] = array($rs->fields['BeginTime'],$rs->fields['Profit']);
						//$floatPips += $itemPips;
						//$userPips += $itemPips;
						//echo "".$itemPips."<br>";
				        $rs->MoveNext();
					}
				}
         } catch(exception $e) {
            if (true == $this->db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }


			//echo "<br>$userPips";
         //echo $userPips;
         return $userPips;
         //return true;

      } //getSubscrData


      /*
	  
	  public function getSubscrData($userID) {
         if( !$this->db ) return false;
         $query = "select user_id,subscr_status,subscr_period,subscr_time from fa_subscriptions where user_id='$userID' and subscr_active='1' ORDER BY subscr_time desc";

         try {
           $rs = $this->db->Execute($query);
	           if ($rs){
					while (!$rs->EOF) {
						$sDays = $rs->fields['subscr_period'];
						$this->subscrTimestmp = intval($rs->fields['subscr_time']);
						$this->subscrDays = $this->subscrDays+$sDays;
				        $rs->MoveNext();
					}
        }
         } catch(exception $e) {
            if (true == $this->db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }
         if ($rs->RecordCount()>0)
         	$this->subscrDaysLeft = intval($this->subscrDays) -  intval((time() - $this->subscrTimestmp) / 86400);
         return	$this->subscrDaysLeft;

      } //getSubscrData
	  
	  
	  
	      public function checkSubscribed($userID) {
	         if( !$this->db ) return false;
	         $query = "select user_id,subscr_status from fa_subscriptions where user_id='$userID' and subscr_active='1'";

	         try {
	           $rs = $this->db->Execute($query);
	         } catch(exception $e) {
	            if (true == $this->db->debug ) {
	              adodb_pr($e);
	              $e = adodb_backtrace($e->trace);
	            }
	            die('DB Error: '.$e->sql);
	         }

	         if ( $rs->RecordCount()>0 ) return true;
	         else return false;


	      } //checkSubscribed



      public function isTrialFinished($userID) {
         if( !$this->db ) return false;
         $query = "select ActivationTime from fa_users where UserID='$userID'";

         try {
           $rs = $this->db->Execute($query);
         } catch(exception $e) {
            if (true == $this->db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }

         $this->trialDaysPassed = $trialDaysPassed = intval((time() - $rs->fields['ActivationTime'])/86400);

         if ( $trialDaysPassed>=$this->TrialDays ) {
         	$this->trialDaysLeft = 0;
         	return true;
         }
         else {
         	$this->trialDaysLeft = $this->TrialDays-$this->trialDaysPassed;
         	return false;
         }

      } //check isTrialFinished

      */


      public function trialDaysLeft($userID) {

         $this->isTrialFinished($userID);
         return $this->trialDaysLeft;

      } //check isTrialFinished

      private function getPeriodDates($dateFrom) {
      	// _form_calc__mnth
         $dtFrom = $dateFrom;
         $dtTo = time();
         $mFrom = date("M",$dtFrom);
         $mTo = date("M",$dtTo);
         $dFrom = date("d",$dtFrom);
         $dTo = date("d",$dtTo);

         $mToLabel = $this->TranslationMessage->GetMessage('_form_calc__mnth'.$mTo);
         $mFromLabel = $this->TranslationMessage->GetMessage('_form_calc__mnth'.$mFrom);

         $pStart = $mFromLabel." ".$dFrom;
         $pEnd = $mToLabel." ".$dTo.", ".date("Y",$dtTo);

         $period = array($pStart,$pEnd);
         //$period = array($mFrom,$mTo);

         return $period;
      } //check getPeriodDates


      public function sendMail($email,$name,$lang,$period) {
      		//$email = "alexander.ganchuk@gmail.com";
      		$ImageName = $name.$this->gImageName; //form custom image name
            if( $this->loging ) $this->StartLog();
            global $config;
            $mailTemplate = $this->mailMode.'.tpl';
        	$subscrLink = $config['host']['root']."/index.php?p=rates&s=subscribe&lang=$lang";
        	//$subscrLink = $this->TranslationMessage->GetMessage('_fxbanner__banner_caption');

       		$Mailer = new objMailer();
       		$Mailer->Priority = 3; //normal priority
	        $Mailer->isHTML( true );
	        $Mailer->AddAddress($email,$name);
	        $Mailer->AddBcc($this->supportAddr);
	        $Mailer->AddBcc("ivan.khitko@gmail.com");
	        //$Mailer->AddBcc("khitko@ukr.net");
	        //$Mailer->AddBcc("alexander.ganchuk@gmail.com");
	        //$Mailer->Subject = $this->mailSubject;
	        $Mailer->Subject = $this->TranslationMessage->GetMessage('mail_subject__email_trial');
			$Mailer->FromName = $this->TranslationMessage->GetMessage('mail_from__i4x_service'); //$config['mailer']['fromName']
			$Mailer->From = $this->supportFromAddr;
			if ($this->mailMode=="EmailTrial") {
				//$Mailer->AddEmbeddedImage($this->gImagePath,12,$ImageName,"base64","image/gif");
			}

	  		$BodyTemplate = new objTemplate();
	  		$BodyTemplate->Assign('image', $ImageName);
	  		$BodyTemplate->Assign('lang', $lang);
	    	$BodyTemplate->Assign('userName', $name);
	    	$BodyTemplate->Assign('period_start', $period[0]);
	    	$BodyTemplate->Assign('period_end', $period[1]);
	    	$BodyTemplate->Assign('subscrLink', $subscrLink);
	  		$BodyTemplate->Fetch($this->mailTemplate);
	    	$Mailer->Body = $BodyTemplate->Fetch($this->mailTemplate);


           $this->setLogContent($email." | ");

			$result = $Mailer->Send();

	    	if( $this->loging ) {
                        $log_data = $Mailer->Message;
                        $log_data['result'] = $Mailer->ErrorInfo;
                        $this->Log->Add( new objMailerLogRecord($log_data) );
                        $this->Log->Flush();
                        unset($log_data);
      		}//logging
      		$Mailer->ClearAddresses();

	    	$this->setLogContent(" \r\n");
		sleep(1);
	    	return true;

     } //sendMail

     // notify support about new subscriber
     public function subscrNotify($email1,$uid,$subscrTime,$subscrLength,$notifyType,$paymentMethod=false) {


     		//if( $this->loging ) $this->StartLog();
      		$email = 'alexander.ganchuk@gmail.com';
      		if ($notifyType=='subscr_new') $bTemplate = 'EmailSubscrNotify.tpl';

       		$Mailer = new objMailer();
       		$Mailer->Priority = 3; //normal priority
	        $Mailer->isHTML( true );
	        $Mailer->AddAddress($this->supportAddr,$name);
	        //$Mailer->AddAddress($this->supportAddr1,$name);

	        $Mailer->Subject = "Intelli4x Subscription Notification";
			$Mailer->From = $this->supportFromAddr;
			$Mailer->FromName = "Subscription Notifier";
	  		$BodyTemplate = new objTemplate();
	    	$BodyTemplate->Assign('uid', $uid);
			$BodyTemplate->Assign('method', $paymentMethod);
	    	$BodyTemplate->Assign('email', $email1);
	    	$BodyTemplate->Assign('stime', date("Y-m-d G:i:s",$subscrTime));
	    	$BodyTemplate->Assign('slength', round($subscrLength/30));
	    	$BodyTemplate->Fetch($bTemplate);
	    	$Mailer->Body = $BodyTemplate->Fetch($bTemplate);

            $this->setLogContent($email." | ");

			$result = $Mailer->Send();

      		$Mailer->ClearAddresses();
            $this->setLogContent(" \r\n");
	    	return true;

     } //subscrNotify


     public function subscrEnding($email,$name,$days,$notifyType,$lang,$system=false) {
			$subject = $this->TranslationMessage->GetMessage('mail_subject__email_subscribtion')." (".$system.")";
	 
            if( $this->loging ) $this->StartLog();
			if ($days==0) {
				$bTemplate = 'EmailSubscrEnd.tpl';
				$subject = $this->TranslationMessage->GetMessage('mail_subject__email_subscr_end')." (".$system.")";
			}
            else if ($notifyType=='subscr_ending') {
				$bTemplate = 'EmailSubscrDays.tpl';
			}
      		else if ($notifyType=='refund') $bTemplate = 'EmailSubscrRefund.tpl';

       		$Mailer = new objMailer();
       		$Mailer->Priority = 3; //normal priority
	        $Mailer->isHTML( true );
	        $Mailer->AddAddress($email,$name);
	        $Mailer->AddBcc($this->supportAddr);
			$this->TranslationMessage->SetLang($lang);

	        //$Mailer->Subject = $this->subject;
	        $Mailer->Subject = $subject;
			$Mailer->From = $this->supportFromAddr;
			$Mailer->FromName = $this->TranslationMessage->GetMessage('mail_from__i4x_service');

	  		$BodyTemplate = new objTemplate();
	    	$BodyTemplate->Assign('name', $name);
	    	$BodyTemplate->Assign('days', $days);
	    	$BodyTemplate->Assign('lang', $lang);
			$BodyTemplate->Assign('system', $system);
	    	$BodyTemplate->Fetch($bTemplate);
	    	$Mailer->Body = $BodyTemplate->Fetch($bTemplate);


            $this->setLogContent($email." | ");

			$result = $Mailer->Send();

      		$Mailer->ClearAddresses();
            $this->setLogContent(" \r\n");
	    	return true;

     } //subscrNotify

// function for SMS sending testing (Clickatell)
     public function testSMSEmail($phone=false) {
     		global $config;
     		if( $this->loging ) $this->StartLogSMS();
     		$bTemplate ='SMStest.tpl';
       		$Mailer = new objMailer();
       		$Mailer->Priority = 3; //normal priority
	        $Mailer->isHTML( false );

	        $Mailer->AddAddress('sms@messaging.clickatell.com');
	        $Mailer->AddBcc('alexander.ganchuk@gmail.com');
	        //$Mailer->AddAddress('alexander.ganchuk@gmail.com');
	        //$Mailer->AddAddress('sms@messaging.clickatell.com');

	        if (!$phone) $phone="380679683938";

	        $subject = 'FORECAST';


            $BodyTemplate = new objTemplate();
            $BodyTemplate->Assign('phone',$phone);
            $BodyTemplate->Assign('user', $config['sms']['user']);
			$BodyTemplate->Assign('pass', $config['sms']['pass']);
			$BodyTemplate->Assign('api_id', $config['sms']['api_id']);
	    	$BodyTemplate->Fetch($bTemplate);
	    	$Mailer->Body = $BodyTemplate->Fetch($bTemplate);


	        $Mailer->Subject = $subject;
			$Mailer->From = $this->supportFromAddr;
			$Mailer->FromName = $this->TranslationMessage->GetMessage('mail_from__i4x_service');

			$Mailer->Send();

	    	if( $this->loging ) {
                        $log_data = $Mailer->Message;
                        $log_data['result'] = $Mailer->ErrorInfo;
                        $this->Log->Add( new objMailerLogRecord($log_data) );
                        $this->Log->Flush();
                        unset($log_data);
      		}//logging

      		$Mailer->ClearAddresses();
	    	return true;

     } //testSMSEmail


     public function setMailContent() {
     	global $config;
     	//$this->mailSubject = $this->TranslationMessage->GetMessage('email_subject__trial_ptolongation');
        $this->mailTemplate = $this->mailMode.'.tpl';


	} // setMailContent

     //--------------------------------------------------------------------------------------------------

     // get emails array of users that are not subscribed and not notified yet about their trial period end
     public function getEmailsArr() {
     	$query = "select UserID,Name,Login,Active,ActivationTime,Notifications,Language from fa_users where Active='1' and TrialNotification='0' order by UserID asc";
		try {
           $rs = $this->db->Execute($query);
         } catch(exception $e) {
            if (true == $this->db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }

        if ($rs) {
			while (!$rs->EOF) {
				if (!$this->isTrialFinished($rs->fields['UserID']) && $this->trialDaysLeft==3) {
					echo $rs->fields['Login']." - ".$this->isTrialFinished($rs->fields['UserID'])." 3 days left<br>";
					$this->emailsArr3[] = $rs->fields['Login'];
					$this->namesArr3[] = $rs->fields['Name'];
				}
				//echo $this->isTrialFinished($rs->fields['UserID']).$rs->fields['UserID']."<br>";
				if (!$this->checkSubscribed($rs->fields['UserID']) && $this->isTrialFinished($rs->fields['UserID'])) {
					echo $rs->fields['Login']." - ".$this->isTrialFinished($rs->fields['UserID'])." trial finished<br>";
					$this->emailsArr[] = $rs->fields['Login'];
					$this->namesArr[] = $rs->fields['Name'];
					$this->langArr[] = $rs->fields['Language'];
					$this->activeArr[] = $rs->fields['ActivationTime'];
					//$this->getNotificationsArr($rs->fields['Notifications']);
				}
		        $rs->MoveNext();
			}
		}

	} //getEmailsArr

	//////////////////////////////////////////////////////////////////////////////
	 // get emails array of subscribed users
     public function getSubscribedEmail($days) {
     	$currID;
     	$query = "SELECT u.UserID,u.Login,u.Name,u.Language,s.subscr_id,s.subscr_system, ".
		" (SELECT ss.Name FROM fa_systems ss WHERE s.subscr_system=ss.SystemID) as Sysname, ".
		" ROUND(((s.subscr_system_date+s.subscr_system_period*86400)-UNIX_TIMESTAMP())/86400) as system_days_left ".
		" FROM fa_users u LEFT JOIN fa_subscriptions s ON s.user_id = u.UserID ".
		" WHERE s.subscr_active=1 ORDER BY s.user_id,s.subscr_time asc";

           $rs = $this->db->Execute($query);
		   
			while (!$rs->EOF) {
				$currID = $rs->fields['UserID'];
				//$subscrData = $this->getSubscrData($currID);
				

				$currDasys = $rs->fields['system_days_left'];
				
				echo $days." ".$currDasys."<br>";
				
				//deactivate subscription
				if($days==0 && $currDasys<=0){
					//echo $rs->fields['UserID']." ".$rs->fields['Login']." $currDasys Subscrdays<br>";
					
					$this->userList[] = array(
						'email' => $rs->fields['Login'],
						'name' =>  $rs->fields['Name'],
						'lang' =>  $rs->fields['Language'],
						'system' =>  $rs->fields['Sysname']);
					$subscr = new objUserSubscription();
					$subscr->terminateUserSubscription($rs->fields['UserID'],
														$rs->fields['subscr_id'],
														$rs->fields['subscr_system']);
														
					var_dump ($this->userList);
					echo "<br>".$currDasys." days left<br>";								
				}
				
				else if($currDasys==$days){
					//echo $rs->fields['Login']." - ".$rs->fields['Name']." - ".date("Y-m-d")." $days<br>";
					
					$this->userList[] = array(
						'email' => $rs->fields['Login'],
						'name' =>  $rs->fields['Name'],
						'lang' =>  $rs->fields['Language'],
						'system' =>  $rs->fields['Sysname']);
						
					var_dump ($this->userList);
					echo "<br>".$currDasys." days left<br>";
				}
				
		        $rs->MoveNext();
			}

	} //getSubscribedEmail
	
	/*
	public function getSubscribedEmail($days) {
     	$currID;
     	$userPips = $this->getUserPips();
     	$query = "SELECT u.UserID,u.Login,u.Name,u.Language,s.user_id,s.subscr_time,s.subscr_time,s.subscr_type FROM fa_users u LEFT JOIN fa_subscriptions s ON s.user_id = u.UserID WHERE s.subscr_active=1 ORDER BY s.user_id,s.subscr_time asc";
		try {
           $rs = $this->db->Execute($query);
            if ($rs) {
			while (!$rs->EOF) {

				if($currID == $rs->fields['UserID']){
					$this->subscrDays = 0;
      				$this->subscrDaysLeft = 0;
				}
				$currID = $rs->fields['UserID'];
				$currDasys = $this->getSubscrData($rs->fields['user_id']);
				//echo $days." ".$currDasys;
                if($currDasys==$days){
					echo $rs->fields['Login']." - ".$rs->fields['Name']." - ".date("Y-m-d",$rs->fields['subscr_time'])." $days<br>";
					//echo "<br>- ".$this->getSubscrData($rs->fields['user_id'])." -<br>";
					$this->emailsArr[] = $rs->fields['Login'];
					$this->namesArr[] = $rs->fields['Name'];
					$this->langArr[] = $rs->fields['Language'];

					// check if today last susbscription day and this is not a trial subscription
					if($days==1 && $rs->fields['subscr_type']!="D" && $userPips<100){

                         echo $rs->fields['Login']." - ".$rs->fields['Name']." pips earned: ".$userPips."<br>";
                         $this->refundArr .= $rs->fields['Login']." - ".$rs->fields['Name']." pips earned: ".$userPips."<br>";

					}
					if($days==0){

                         echo $rs->fields['UserID']." ".$rs->fields['Login']." $currDasys Subscrdays<br>";
                         $this->deactivateSubscription($rs->fields['UserID']);
					}
				}

				//deactivate subscription


		        $rs->MoveNext();
			}
		}
         } catch(exception $e) {
            if (true == $this->db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }



	} //getEmailsArr
	*/


	// notify by email users that are not subscribed and not notified yet about their trial period end
	public function notifyTrialEnd() {
		$dateFrom;
		//$dateFrom = date("Y-m-d G:i:s",time()-14*86400);
		$dateTo = date("Y-m-d G:i:s");

		//$dateFrom = "2007-10-15 11-11-11";
		//$dateTo = "2007-10-29 11-11-11";


        $cnter=0;
     	foreach ($this->emailsArr as $email) {
            $query="";
            //$notification = $this->notificationsArr[$cnter].$this->mailMode.","; //Set notification type
            $timeFrom = $this->activeArr[$cnter];
            $dateFrom = date("Y-m-d G:i:s",$timeFrom);
            echo $dateFrom;
            //$this->gImagePath = strval($this->generatePerfGraph($dateFrom,$dateTo));

            //set language for current user
            $lang = $this->langArr[$cnter];
            $this->TranslationMessage->SetLang($lang);

     		if ($this->sendMail($email,$this->namesArr[$cnter],$lang,$this->getPeriodDates($timeFrom))) {
     			$query="update fa_users set TrialNotification='1' where Login='$email'";
        		try {
		           $rs = $this->db->Execute($query);
		        }
		        catch (exception $e) {
		            if (true == $this->db->debug ) {
		              adodb_pr($e);
		              $e = adodb_backtrace($e->trace);
		            }
		            die('DB Error: '.$e->sql);
		        }
		    }
           	$cnter++;
     	}

	} //notifyTrialEnd

	// notify by email users that are not subscribed and not notified yet about their trial period end
	public function notifyTrial3days() {
        $cnter=0;
     	foreach ($this->emailsArr3 as $email) {

     		$this->sendMail($email,$this->namesArr3[$cnter]);
     	}

	} //notifyTrial3days

    // notifications from admin panel
	public function sendNotifications() {
        $cnter=0;
     	foreach ($this->emailsArr as $email) {
            $query="";
            //$notification = $this->notificationsArr[$cnter].$this->mailMode.","; //Set notification type
     		$this->sendMail($email,$this->namesArr[$cnter]);
           	$cnter++;
     	}

	} //notifyTrialEnd


	// notify by email users that are subscribed
	public function notifySubscrEnd($days) {
     	foreach ($this->userList as $user) {
     		$this->subscrEnding($user['email'],$user['name'],$days,'subscr_ending',$user['lang'],$user['system']);
     	}

		// send notification to support if system earned less thasn 100 pip during last month
		//echo "_".$this->refundArr."_";
		//if($days==1 && $this->refundArr!="") $this->subscrEnding('og@cid.kiev.ua','',$this->refundArr,'refund');

	} //notifySubscrEnd


 // notify by email users that should be refunded
	public function notifySubscrRefund() {
		$cnter=0;
     	//foreach ($this->emailsArr as $email) {

     		$this->subscrEnding($email,$this->refundArr,'','refund');
     		$cnter++;
     	//}

	} //notifySubscrRefund



	// notifyNewFeatures
	public function notifyNewFeatures() {
        $cnter=0;
        $cnterme=0;

     	foreach ($this->emailsArr as $email) {

     		$this->newFeatures($email,$this->namesArr[$cnter],'newf',$this->langArr[$cnter],$cnter);
           	$cnter++;
     	}

		// send notification to support if system earned less thasn 100 pip during last month
		//echo "_".$this->refundArr."_";
		//if($days==1 && $this->refundArr!="") $this->subscrEnding('og@cid.kiev.ua','',$this->refundArr,'refund');

	} //notifyNewFeatures


	     public function newFeatures($email,$name,$notifyType,$lang) {

            if( $this->loging ) $this->StartLog();
            if ($notifyType=='newf') $bTemplate = 'EmailNewFeatures.tpl';

       		$Mailer = new objMailer();
       		$Mailer->Priority = 3; //normal priority
	        $Mailer->isHTML( true );
	        $Mailer->AddAddress($email,$name);
	        $Mailer->AddBcc("og@cid.kiev.ua");
			//$this->TranslationMessage->SetLang($lang);

	        $Mailer->Subject = "IntelliForex Launches Intraday System & Direct SMS Alerts";
			$Mailer->From = $this->supportFromAddr;
			$Mailer->FromName = "IntelliForex Support";

	  		$BodyTemplate = new objTemplate();
	  		$BodyTemplate->Assign('name', $name);
	    	$BodyTemplate->Fetch($bTemplate);
	    	$Mailer->Body = $BodyTemplate->Fetch($bTemplate);


            $this->setLogContent($email." | ");

			//$result = $Mailer->Send();
            usleep(250000);
      		$Mailer->ClearAddresses();
            $this->setLogContent(" \r\n");
	    	return true;

     } //subscrNotify

      public function send2Me() {

            $bTemplate = 'EmailNewFeatures.tpl';

       		$Mailer = new objMailer();
       		$Mailer->Priority = 3; //normal priority
	        $Mailer->isHTML( true );
	        $Mailer->AddAddress('og@cid.kiev.ua');

	        $Mailer->Subject = "IntelliForex Launches IntraDay System & Direct SMS Alerts";
			$Mailer->From = $this->supportFromAddr;
			$Mailer->FromName = "IntelliForex Support";

	  		$BodyTemplate = new objTemplate();
	  		$BodyTemplate->Assign('name','Alex');
	    	$BodyTemplate->Fetch($bTemplate);
	    	$Mailer->Body = $BodyTemplate->Fetch($bTemplate);


            $this->setLogContent($email." | ");

			$result = $Mailer->Send();
      		$Mailer->ClearAddresses();
            $this->setLogContent(" \r\n");
	    	return true;

     } //subscrNotify


     public function getTrialArr() {
     	$query = "select UserID,Name,Login,Active,ActivationTime,Notifications,Language from fa_users where Active='1' and TrialNotification='0' order by UserID asc";
		try {
           $rs = $this->db->Execute($query);
         } catch(exception $e) {
            if (true == $this->db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }

        if ($rs) {
			while (!$rs->EOF) {
				if (!$this->isTrialFinished($rs->fields['UserID']) && !$this->checkSubscribed($rs->fields['UserID'])) {
					echo $rs->fields['Login']." - ".$this->trialDaysLeft."<br>";
					$this->emailsArr[] = $rs->fields['Login'];
					$this->namesArr[] = $rs->fields['Name'];
					$this->langArr[] = $rs->fields['Language'];
					$this->activeArr[] = $rs->fields['ActivationTime'];
				}
		        $rs->MoveNext();
			}
		}

	} //



    //--------------------------------------------------------------------------------------------------

     public function getNotificationsArr($notification) {

			if ($notification)
				$this->notificationsArr[] = $notification;
			else
				$this->notificationsArr[] = "";

		    return true;

	} //getNotificationsArr


    public function writeLog($logFile) {
		// LOG ALL EVENTS ////
		$logDate = date("Y-m-d h:i:s")." -> "; //date for log file
		$fd = fopen("../logs/".$logFile.".log", "a");
		fwrite($fd, "\r\n".$logDate."\r\n".$this->logContent);
		fclose($fd);
	} //wrtieLog

	private function setLogContent($logContent) {
		// LOG ALL EVENTS ////
		$this->logContent.= $logContent;
		return true;
	} //setLogConyrnt


	private function getTextCaption($logContent) {
		// LOG ALL EVENTS ////
		$this->logContent.= $logContent;
		return true;
	} //setLogConyrnt


	protected function generatePerfGraph ($time_from,$time_to) {
        	$Calculator = new objCalculator();

		    $Calculator->timeRange[0] = DateConvert::Date2('U', $time_from);//$start;
		    $Calculator->timeRange[1] = DateConvert::Date2('U', $time_to);//$finish;
		    $Calculator->slippage = 0;
		    $Calculator->contract = 10000;
		    $Calculator->balance = 100000;
		    $Calculator->deposit = 10000;
		    //$Calculator->trades = array('2400304','2400103','2400203','2400306','2400503');
		    $Calculator->trades = array('2400103');

		    $CalcPlotGenerator = new objCalcPlotGenerator($Calculator);
		    $CalcPlotGenerator->clean_image = false;
		    $CalcPlotGenerator->mode = 'day';

		    return $CalcPlotGenerator->Render();
        }


   }

////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////

class objDataProviderFail extends objMailshot{

	var $lastRate; // latest rate time
	//var $checkPeriod = $config['rates']['age']; // rates shouldn't be older than ... seconds


	function __construct() {
       $db = $this->db = objDataBase::GetInstance();//new objDataBase();
		parent::__construct();
 	} //constructor


	public function checkLastRate() {
		global $config;
		$this->getLastRateTime();
		$currDay = date("D",time());
		//$currHour = date("H",time());
		$isNotified = 1;

		if ((time()-intval($this->getVarFromFile("dataProvFail"))) > 5*$config['rates']['age']) $isNotified = 0;

		if ((time() - $this->lastRate)>$config['rates']['age'] && $currDay!="Sat" && $currDay!="Sun" && $isNotified!=1){


			echo time() - $this->lastRate."<br>".date('G:i:s d-m-Y',$this->lastRate)." - ".(time() - intval($this->getVarFromFile("dataProvFail")))." - ".$config['rates']['age']."<br>";
			$this->sendProblemNotification();
			$this->writeVarFile("dataProvFail");
		}
		//else {echo "no working";}
		//echo date('G:i:s d-m-Y',$this->lastRate)."<br>";
        return true;
	}

	private function getLastRateTime() {
  		$query="select max(Time) as lastRate from fa_rates";
    	try {
          $rs = $this->db->Execute($query);
          $this->lastRate = $rs->fields['lastRate'];
       }
       catch (exception $e) {
           if (true == $this->db->debug ) {
             adodb_pr($e);
             $e = adodb_backtrace($e->trace);
           }
           die('DB Error: '.$e->sql);
       }
        return $this->lastRate;
	}

	private function sendProblemNotification() {
        global $config;
        $emails = $config['rates']['emails'];
     	//$email = 'og@cid.kiev.ua';
     	//$email = '$this->supportAddr';
     	$bTemplate = 'EmailDataProvFail.tpl';
     	//$bTemplate = 'EmailSubscrNotify.tpl';

      	$Mailer = new objMailer();
      	$Mailer->Priority = 2;
        $Mailer->isHTML( true );
        foreach ($emails as $email){
        	$Mailer->AddAddress($email);
        }

        $Mailer->Subject = "Intelli4x Data Provider Problems";
		$Mailer->From = $this->supportAddr;
		$Mailer->FromName = "Intelli4x Notifier";
  		$BodyTemplate = new objTemplate();
  		$BodyTemplate->Assign('lastRateTime', date('G:i:s d-m-Y',$this->lastRate));
    	$Mailer->Body = $BodyTemplate->Fetch($bTemplate);

		$result = $Mailer->Send();

  		$Mailer->ClearAddresses();
    	return true;

     } //ProblemNotify


    private function writeVarFile($logFile) {
		$fd = fopen("../logs/".$logFile.".log", "w");
		fwrite($fd, time());
		fclose($fd);
	} //writeVarFile

	private function getVarFromFile($logFile) {
		$fd = fopen("../logs/".$logFile.".log", "r");
		//echo is_readable("../logs/".$logFile.".log");
		$fileVar = fread($fd, 10);
		fclose($fd);
		return $fileVar;
	} //getVarFromFile

}


?>
